package com.example.service.impl;

import com.example.service.DocumentApprovalService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 文档审批服务实现类
 */
@Service
public class DocumentApprovalServiceImpl implements DocumentApprovalService {
    
    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private TaskService taskService;
    
    @Override
    public String startApprovalProcess(String documentId, String submitter, Set<String> approverGroups) {
        // 设置流程变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("documentId", documentId);
        variables.put("submitter", submitter);
        variables.put("approverGroups", approverGroups);
        variables.put("approved", false); // 默认未审批通过
        
        // 启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "documentApprovalProcess", variables);
        
        return processInstance.getId();
    }
    
    @Override
    public void completeTask(String taskId, String approver, boolean approved, String comment) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", approved);
        variables.put("approver", approver);
        variables.put("comment", comment);
        
        taskService.complete(taskId, variables);
    }
    
    @Override
    public void cancelProcess(String processInstanceId, String reason) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("cancelled", true);
        variables.put("cancelReason", reason);
        
        runtimeService.setVariables(processInstanceId, variables);
        runtimeService.deleteProcessInstance(processInstanceId, reason);
    }
}